package org.datascooter.extension;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.datascooter.inface.IXMLReader;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.Platform;

public class EclipseExtensionReader implements IXMLReader {

	private final String extensionPointId;
	private List<SimpleElementReader> childList = new ArrayList<SimpleElementReader>();
	private IExtensionPoint extensionPoint;

	public EclipseExtensionReader(String extensionPointId) {
		this.extensionPointId = extensionPointId;
	}

	@Override
	public void explore() {
		extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(extensionPointId);
		for (IExtension ext : extensionPoint.getExtensions()) {
			for (IConfigurationElement element : ext.getConfigurationElements()) {
				childList.add(new SimpleElementReader(element));
			}
		}
	}

	@Override
	public String getAttribute(String name) {
		return null;
	}

	@Override
	public IXMLReader[] getChildren(String name) {
		return childList.toArray(new IXMLReader[childList.size()]);
	}

	@Override
	public String getNamespaceIdentifier() {
		return extensionPoint.getNamespaceIdentifier();
	}

	@Override
	public String getValue(String name) {
		return null;
	}
	private class SimpleElementReader implements IXMLReader {

		private final IConfigurationElement element;

		public SimpleElementReader(IConfigurationElement element) {
			this.element = element;
		}

		@Override
		public void explore() {
		}

		@Override
		public String getAttribute(String name) {
			return element.getAttribute(name);
		}

		@Override
		public IXMLReader[] getChildren(String name) {
			List<SimpleElementReader> childList = new ArrayList<SimpleElementReader>();
			for (IConfigurationElement child : element.getChildren(name)) {
				childList.add(new SimpleElementReader(child));
			}
			return childList.toArray(new IXMLReader[childList.size()]);
		}

		@Override
		public String getNamespaceIdentifier() {
			return element.getNamespaceIdentifier();
		}

		@Override
		public String getValue(String name) {
			return element.getValue();
		}

		@Override
		public String resolvePath(String fileName) {
			try {
				return EclipsePathResolver.resolvePath(fileName);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
	}

	@Override
	public String resolvePath(String fileName) {
		try {
			return EclipsePathResolver.resolvePath(fileName);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
